package com.shanyu.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.json.JsonObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.shanyu.constant.Constants;
import com.shanyu.dto.WxTokenDto;
import com.shanyu.dto.WxUserDto;
import com.shanyu.service.IWxService;

@Service
public class WxServiceImpl implements IWxService{
	
	private Logger logger = LoggerFactory.getLogger(WxServiceImpl.class);
    
    /**
     * 获取请求用户信息的access_token
     *
     * @param code
     * @return
     */
    public WxTokenDto getUserInfoAccessToken(String code) {
    	WxTokenDto dto = null;
        try {
            String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                                       Constants.weCatAppId, Constants.weCatAppSecret, code);
            logger.info("request accessToken from url: {}", url);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String tokens = EntityUtils.toString(httpEntity, "utf-8");
            Object json = JSON.parseObject(tokens,WxTokenDto.class);
            dto = (WxTokenDto)json;
            logger.info(JSON.toJSONString(dto));
        } catch (Exception ex) {
            logger.error("fail to request wechat access token. [error={}]", ex);
        }
        return dto;
    }
    
    /**
     * 获取用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public WxUserDto getUserInfo(String accessToken, String openId) {
    	logger.info("accessToken:"+accessToken+",openId:"+openId);
    	WxUserDto dto = null;
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        logger.info("request user info from url: {}", url);
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            
            Object json = JSON.parseObject(response,WxUserDto.class);
            dto = (WxUserDto)json;
            //logger.info("get userinfo success. [result={}]", wxUser);
        } catch (Exception ex) {
            logger.error("fail to request wechat user info. [error={}]", ex);
        }
        return dto;
    }
    
    
    public static void main(String args[]){
    	String code = "013wPOLG1IjNv70lxdNG1Y9OLG1wPOL";
    	WxServiceImpl service = new WxServiceImpl();
    	WxTokenDto token = service.getUserInfoAccessToken(code);
    	System.out.println(JSON.toJSONString(token));
    	WxUserDto wxUser = service.getUserInfo(token.getSessionKey(), token.getOpenId());
    	System.out.println(JSON.toJSONString(wxUser));
    }

}
